//
//  HyqTeaController.swift
//  约麻
//
//  Created by rimi on 2017/7/12.
//  Copyright © 2017年 Sweet. All rights reserved.
//

import UIKit
import AVOSCloud
import MJRefresh
import MBProgressHUD

class HyqTeaController: UIViewController {
    var locationserivce=BMKLocationService()
    var geocode=BMKGeoCodeSearch()
    var long:Double?
    var lat:Double?
    var searchPOI=BMKPoiSearch()
    var type = BMK_POI_SORT_BY_COMPOSITE
    var dataArray = [ZWHTeaViewModel]()
    var fristin = true
    var isrefresh = true
    var pageindex = 0
    
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var sliderL: UILabel!
    @IBOutlet weak var distancequeB: UIButton!
    @IBOutlet weak var sumqueB: UIButton!
    
    @IBOutlet weak var diantanceL: UILabel!
    
    override func viewWillAppear(_ animated: Bool) {
        
        navigationController?.isNavigationBarHidden = true
        searchPOI.delegate = self
        locationserivce.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        geocode.delegate = nil
        searchPOI.delegate = nil
        locationserivce.delegate = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        geocode.delegate = self
        //启动LocationService
        locationserivce.startUserLocationService()
        sumqueB.isEnabled = false
        
        
        tableview.register(UINib.init(nibName: "ZWHTeaViewCell", bundle: nil), forCellReuseIdentifier: "ZWHTeaViewCell")
        tableview.rowHeight = 80
        
        
        
        tableview.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.isrefresh = true
            self.pageindex = 0
            self.searchpoi()
        })
        
        
        tableview.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { 
            self.isrefresh = false
            if self.dataArray.count == 0{
                self.pageindex = 0
            }else{
                self.pageindex += 1
            }
            self.searchpoi()
        })
        
    }
    
    //综合排序
    @IBAction func sumdownload(_ sender: UIButton) {
        sumqueB.isEnabled = false
        distancequeB.isEnabled = true
        sliderL.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
        diantanceL.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        

        
            self.pageindex = 0
            self.type = BMK_POI_SORT_BY_COMPOSITE
            self.isrefresh = true
            self.searchpoi()
        
    }
    
    //距离排序
    @IBAction func distancedownload(_ sender: UIButton) {
        distancequeB.isEnabled = false
        sumqueB.isEnabled = true
        sliderL.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        diantanceL.backgroundColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
        

            self.pageindex = 0
            self.type = BMK_POI_SORT_BY_DISTANCE
            self.isrefresh = true
            self.searchpoi()
    }
    
    //搜索
    func searchpoi(){
        let option = BMKNearbySearchOption()
        option.pageIndex = Int32(pageindex)
        //option.pageCapacity = 10;
        option.location = CLLocationCoordinate2DMake(lat!, long!)
        option.keyword = "茶楼"
        option.radius = 10000
        option.sortType = type
        
//                    let op = BMKPoiDetailSearchOption()
//                    op.poiUid = "b9b8bff64d28b5bc38e4a6fc"
        //searchPOI.poiSearchNear(by: option)
        MBProgressHUD.showAdded(to: self.tableview, animated: true)
        searchPOI.poiSearchNear(by: option)
        //searchPOI.poiDetailSearch(op)
    }
    
}


extension HyqTeaController:BMKLocationServiceDelegate{
    func didUpdateUserHeading(_ userLocation: BMKUserLocation!) {
        /*BMKCoordinateRegion region ;//表示范围的结构体
         region.center = self.mapView.centerCoordinate;//中心点
         region.span.latitudeDelta = 0.004;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
         region.span.longitudeDelta = 0.004;//纬度范围
         [self.mapView setRegion:region animated:YES]; */
    }
    
    func didUpdate(_ userLocation: BMKUserLocation!) {
        lat = userLocation.location.coordinate.latitude
        long = userLocation.location.coordinate.longitude
        UserDefaults.standard.set(lat, forKey: "userlat")
        UserDefaults.standard.set(long, forKey: "userlong")
        UserDefaults.standard.synchronize()
        if fristin == true {
            searchpoi()
            fristin = false
        }
    }
}

extension HyqTeaController:BMKGeoCodeSearchDelegate{
    //反编码
    func onGetGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        if error == BMK_SEARCH_NO_ERROR {
            let item = BMKPointAnnotation()
            item.coordinate = result.location
            item.title = result.address
            
            let showMessage = "纬度:\(item.coordinate.latitude)，经度:\(item.coordinate.longitude)"
            print(showMessage)
//            
//            let alertView = UIAlertController(title: "正向地理编码", message: showMessage, preferredStyle: .alert)
//            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
//            alertView.addAction(okAction)
//            self.present(alertView, animated: true, completion: nil)
        }
    }
    
    //编码
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        if error == BMK_SEARCH_NO_ERROR {
            print(result.address)
//            let alertView = UIAlertController(title: "反向地理编码", message: result.address, preferredStyle: .alert)
//            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
//            alertView.addAction(okAction)
//            self.present(alertView, animated: true, completion: nil)
        }
        
    }
}

extension HyqTeaController:BMKPoiSearchDelegate{
    func onGetPoiResult(_ searcher: BMKPoiSearch!, result poiResult: BMKPoiResult!, errorCode: BMKSearchErrorCode) {
        if errorCode == BMK_SEARCH_NO_ERROR{
            let arrayM = poiResult.poiInfoList as? [BMKPoiInfo]
            if isrefresh == true {
                dataArray.removeAll()
            }
            for model in arrayM! {
                let viewmodel = ZWHTeaViewModel(tea: model)
                dataArray.append(viewmodel)
            }
            tableview.mj_header.endRefreshing()
            tableview.mj_footer.endRefreshing()
            MBProgressHUD.hide(for: tableview, animated: true)
            tableview.reloadData()
            
        }
        else if errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD{
            //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
            // result.cityList;
            print("起始点有歧义");
            pageindex -= 1
            tableview.mj_header.endRefreshing()
            tableview.mj_footer.endRefreshing()
            MBProgressHUD.hide(for: tableview, animated: true)
        } else {
            print("抱歉，未找到结果");
            pageindex -= 1
            tableview.mj_header.endRefreshing()
            tableview.mj_footer.endRefreshing()
            MBProgressHUD.hide(for: tableview, animated: true)
        }
        
    }
    func onGetPoiDetailResult(_ searcher: BMKPoiSearch!, result poiDetailResult: BMKPoiDetailResult!, errorCode: BMKSearchErrorCode) {
        if errorCode == BMK_SEARCH_NO_ERROR{
            print(poiDetailResult.debugDescription,poiDetailResult.description,poiDetailResult.price,poiDetailResult.detailUrl)
        }
    }
}

extension HyqTeaController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "ZWHTeaViewCell", for: indexPath) as? ZWHTeaViewCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let nav = UIApplication.shared.keyWindow?.rootViewController as! UINavigationController
        let vc = UIStoryboard(name: "ZWHTeaDetailViewController", bundle: nil).instantiateViewController(withIdentifier: "ZWHTeaDetailViewController") as! ZWHTeaDetailViewController
        vc.name = dataArray[indexPath.row].tea.name
        vc.opid = dataArray[indexPath.row].tea.uid
        nav.pushViewController(vc, animated: true)
    }
}

